<?php
require APPPATH.'libraries/ApiController.php';
class admin extends ApiController {
	public $AppId="wx6159f2e8742fe1d5";
	public $AppSecret="9b2c163c22a7391f67954ecdff45226b";
	public $EncryptKey="memebersystem";
	
	public function __construct()
	{
		parent::__construct();
	}

	public function wxlogin(){
		$data=$this->getKeys([
		["code",true,"微信账户标识"]],'post');
		
		$code=$data["code"];
		//获取用户openid
		$APPID="wxc454b4a7f424db36";
		$APPSECRET="e9bcf967d44a3231ec3facf1a212f4f3";
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$APPID.'&secret='.$APPSECRET.'&js_code='.$code.'&grant_type=authorization_code';
		
		//进行请求
		$response = file_get_contents($url);
		$data=json_decode($response,true);
		
		$session_key=$data["session_key"];
		$wxopenid=$data["openid"];
		
		
		//查看此openid是否存在
		$user=$this->db->where("wxopenid",$wxopenid)->get("user")->row_array();
		if(!$user){
			$hash =hash('sha256', microtime(true). mt_rand(). uniqid());
			$uid=substr($hash,0,16);
			$uid=strtoupper($uid);
			$this->db->insert("user",array("wxopenid"=>$wxopenid,"uid"=>$uid,"nickname"=>"微信用户","mobile"=>"","avatar"=>"","gender"=>'男'));
		}
		$user=$this->db->where("wxopenid",$wxopenid)->get("user")->row_array();
		
		$tokenArr=array(
			"uid"=>$user["uid"],
			"mobile"=>$user["mobile"],
			"avatar"=>$user["avatar"],
			"nickname"=>$user["nickname"]);
		
		$token=$this->createToken($tokenArr);
		
		$this->WRITE("userinfo",$user);
		$this->WRITE("token",$token);
		$this->RESPONSE();
	}
	
	public function login(){
		$data=$this->getKeys([
		["mobile",true,"手机号码"],
		["password",true,"登录密码"],
		],'post');

		$this->db->select("uid,mobile,nickname,avatar,gender,password,memo,address,email,birth,idcard,admin.shopid,admin_role.roleid,admin_role.roletitle");
		$this->db->join("admin_role","admin_role.roleid=admin.roleid","left");
		$this->db->where("mobile",$data["mobile"]);
		$user=$this->db->get("admin")->row_array();
		if($user){
			if($user["password"]==$data["password"]){
				//查询名下店铺
				$this->db->where("shopid",$user["shopid"]);
				$this->db->select("shopid,title,default,leader,uid,classify,mobile,logo,address,createtime");
				$shop=$this->db->get("shop")->row_array();
				if($shop){
					if($shop["logo"]!=""){
						$shop["logo"]=$this->config->item("domain").$shop["logo"];
					}
				}
				//构建token
				$tokendata=array(
					"uid"=>$user["uid"],
					"nickname"=>$user["nickname"],
					"roleid"=>$user["roleid"],
					"mobile"=>$user["mobile"],
					"roletitle"=>$user["roletitle"],
					"shopid"=>$shop==null? -1:$shop["shopid"]
				);
				
	
				$token=$this->createToken($tokendata);
				
				$user["avatar"]=$user["avatar"]==""?"":$this->config->item("domain").$user["avatar"];
 
				$this->WRITE("userinfo",$user);
				$this->WRITE("shop",$shop);
				$this->WRITE("tokendata",$tokendata);
				$this->WRITE("token",$token);
				$this->WRITE("code",1);
				$this->RESPONSE();
				exit();
			}
		}

		$this->WRITE("msg","手机号或密码不正确!");
		$this->WRITE("code",0);
		$this->RESPONSE();
	}
	
	//新建员工
	public function create(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["username",true,"会员姓名"],
			["mobile",true,"会员手机号"],
			["gender",true,"会员性别"],
			["avatar",false,"头像",""],
			["birth",false,"会员生日",""],
			["idcard",false,"身份证号",""],
			["password",false,"登录密码","123456"],
			["email",false,"电子邮件",""],
			["address",false,"会员地址",""],
			["memo",false,"备注信息",""]],'post');
		
		
		//查询此店铺是否有同名手机
		$this->db->where("mobile",$data["mobile"]);
		$this->db->where("shopid",$token["shopid"]);
		$count=$this->db->select("count(*) as count")->get("admin")->row_array()["count"];
		if($count>0){
			$this->WRITE("msg","该手机已被使用!");
			$this->WRITE("code",0);
			$this->RESPONSE();
			exit();
		}
		
		$data["nickname"]=$data["username"];
		unset($data["username"]);

		$data["shopid"]=$token["shopid"];
		$this->db->insert("admin",$data);
		$this->WRITE("msg","新增员工成功!");
		$this->WRITE("code",1);
		$this->RESPONSE();
		}
	}
	
	
	
	
	public function list(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["query",false,"会员姓名",""]],'post');
			
			$this->db->select("uid,mobile,nickname,gender,avatar,admin.roleid,roletitle,address,email,birth,idcard,admin.shopid,memo");
			$this->db->join("admin_role","admin_role.roleid=admin.roleid","left");
			$this->db->where("admin.shopid",$token["shopid"]);
			$this->db->where("admin.shopid=".$token["shopid"]." and (nickname like '%".$data["query"]."%' or mobile like '%".$data["query"]."%')");
			$users=$this->db->get("admin")->result_array();
		 
			$this->WRITE("msg","查询成功!");
			$this->WRITE("list",$users);
			$this->WRITE("code",1);
			$this->RESPONSE();
		}
	}
	

	public function register(){
		$data=$this->getKeys([
		["mobile",true,"手机号码"],
		["password",true,"密码"]
		],'post');
		
		$data["nickname"]="用户".mt_rand(100,999);
		$this->db->where("mobile",$data["mobile"]);
		$count=$this->db->select("count(*) as count")->get("admin")->row_array()["count"];
		if($count>0){
			$this->WRITE("msg","此手机号已经注册!");
			$this->WRITE("code",0);
			$this->RESPONSE();
			exit();
		}
		$this->db->insert("admin",$data);
		$this->WRITE("msg","注册成功!");
		$this->WRITE("code",1);
		$this->RESPONSE();
	}
	
	public function update(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["uid",true,"UID"],
			["nickname",true,"会员姓名"],
			["mobile",true,"会员手机号"],
			["gender",true,"会员性别"],
			["avatar",false,"头像","https://uiadmin.net/uview-plus/album/3.jpg"],
			["birth",false,"会员生日",""],
			["idcard",false,"身份证号",""],
			["password",false,"登录密码",""],
			["email",false,"电子邮件",""],
			["address",false,"会员地址",""],
			["memo",false,"备注信息",""]],'post');
		
			//查询手机是是否已注册
			$user=$this->db->where("mobile",$data["mobile"])->get("admin")->row_array();
			if($data["password"]==""){
				unset($data["password"]);
			}
			$oAvatar=$user["avatar"];
			//判断是否删除原图片
			if($data["avatar"]==""){
				if($oAvatar!=""){
					//删除原图片
					if(file_exists($this->config->item("upload").$oAvatar)){
						unlink($this->config->item("upload").$oAvatar);
					}
				}
				
				if (!file_exists($this->config->item("upload")."/uploads/avatar/")) {
				    mkdir($this->config->item("upload")."/uploads/avatar/", 0777, true);
				}
				//var_dump("删除了原图片,开始上传新图");
				foreach ($_FILES as $key => $file) {
					if (strpos($file["type"], 'image') !== false  ) {
						$ext = substr(strrchr($file["type"], "/"), 1);
						$filename = 'admin_'.uniqid().'.'.$ext;
						$path='/uploads/avatar/'.$filename;
						if (move_uploaded_file($file["tmp_name"],$this->config->item("upload").$path)) {
							//上传成功
							$data["avatar"]=$path;
						}
					}
				}
				
				
			}else{
				//var_dump("没替换，保持不变");
				$data["avatar"]=str_replace($this->config->item("domain"),"",$data["avatar"]);
				
			}			
			
			if($user){
							


					$this->db->where("uid",$data["uid"]);
					$this->db->update("admin",$data);
					$this->WRITE("code",1);
					$this->WRITE("msg","操作成功!");
					$this->RESPONSE();
					exit();
			}else{
				$this->db->where("uid",$data["uid"]);
				$this->db->update("admin",$data);
				$this->WRITE("code",1);
				$this->WRITE("msg","操作成功!");
				$this->RESPONSE();
			}
		}
		
	}
}
